package com.navinfo.smap;

import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.oscim.android.MapPreferences;
import org.oscim.android.MapView;
import org.oscim.core.MapPosition;
import org.oscim.map.Map;

public abstract class BaseMapActivity extends AppCompatActivity {
    private static final String KEY_LATITUDE = "latitude";
    private static final String KEY_LONGITUDE = "longitude";
    private static final String KEY_MAP_SCALE = "map_scale";
    private static final String PREFERENCES_FILE = "MapActivity";

    private static boolean containsViewport(SharedPreferences sharedPreferences) {
        return sharedPreferences.contains(KEY_LATITUDE)
                && sharedPreferences.contains(KEY_LONGITUDE)
                && sharedPreferences.contains(KEY_MAP_SCALE);
    }

    protected Map mMap;
    protected MapView mMapView;
    protected MapPreferences mPrefs;
    public Map map() {
        return mMap;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPrefs = new MapPreferences(BaseMapActivity.class.getName(), this);
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPrefs.save(mMapView.map());
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        if (!mPrefs.load(mMapView.map())){
            // 如果此前没有保存过地图位置信息，默认定位到北京
            MapPosition mapPosition = new MapPosition();
            mapPosition.setPosition(39917149 / 1E6, 116403696 / 1E6);
            mapPosition.setScale(12);
        }
    }

    @Override
    protected void onStop() {
        mMapView.onPause();
        super.onStop();
    }

    public abstract void updateCurrentLocation(Location location);
}
